package admin

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"miaoyu/internal/dao"
	"miaoyu/internal/service"

	modelAdmin "miaoyu/internal/model/admin"
	"miaoyu/internal/model/entity"
)

type sLevel struct {
}

func init() {
	service.RegisterLevel(NewLevel())
}

func NewLevel() *sLevel {
	return &sLevel{}
}

func (s *sLevel) GetPageList(ctx context.Context, options modelAdmin.UserListInput) (list []modelAdmin.UserLevelOutput, count int, err error) {
	var condition g.MapStrAny
	var pageLimit modelAdmin.PageLimit
	if options.Keywords != "" {
		condition = make(g.MapStrAny)
		condition["title like ?"] = "%" + options.Keywords + "%"
	}
	pageLimit.Start = (options.Page - 1) * options.Limit
	pageLimit.Limit = options.Limit
	fmt.Println("condition", condition)
	resList, resCount, resErr := dao.MyUserLevel.GetPageList(ctx, condition, pageLimit)

	if resErr != nil {
		err = resErr
		return
	}
	count = resCount

	scanErr := gconv.Scan(resList, &list)
	if scanErr != nil {
		err = gerror.New("获取数据错误")
		return
	}

	return
}
func (s *sLevel) checkSubmit(ctx context.Context, data modelAdmin.UserLevelSubmitInput) (err error) {
	//检查是否有重复的职级编码
	_, resErr := dao.MyUserLevel.GetItem(ctx, g.MapStrAny{"code_name": data.CodeName})
	if resErr != nil && resErr != sql.ErrNoRows {
		err = gerror.New("数据获取错误")
		return
	}
	if resErr != sql.ErrNoRows {
		err = gerror.New("职级编码已存在")
		return
	}

	return
}
func (s *sLevel) GetItemById(ctx context.Context, id int64) (res entity.MyUserLevel, resErr error) {
	res, resErr = dao.MyUserLevel.GetItemById(ctx, id)
	if resErr != nil && resErr != sql.ErrNoRows {
		resErr = gerror.New("检索错误")
		return
	}
	if resErr == sql.ErrNoRows {
		resErr = gerror.NewSkip(404, "数据不存在")
		return
	}
	return
}
func (s *sLevel) Add(ctx context.Context, options modelAdmin.UserLevelSubmitInput) (res sql.Result, err error) {
	checkErr := s.checkSubmit(ctx, options)
	if checkErr != nil {
		err = checkErr
		return
	}
	res, err = dao.MyUserLevel.Add(ctx, options)
	if err != nil {

		return
	}
	return
}
func (s *sLevel) Edit(ctx context.Context, options modelAdmin.UserLevelSubmitInput, resId int64) (res sql.Result, err error) {
	res, err = dao.MyUserLevel.UpdateItemById(ctx, options, resId)

	if err != nil {
		return
	}

	return
}

func (s *sLevel) Del(ctx context.Context, resId int64) (sqlAffectRows int64, err error) {

	sqlAffectRows, err = dao.MyUserLevel.DeleteItemById(ctx, resId)
	if err != nil {
		err = gerror.NewSkip(404, "菜单删除失败")
		return
	}
	if sqlAffectRows == 0 {
		err = gerror.New("请求的信息不存在")
		return
	}

	return
}
